package com.atguigu.tingshu.order.config;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

/***
 * 在项目初始化加载的时候加载私钥到IOC的容器中去
 */
@Configuration
public class OrderPrivateKeyConfig {

    /**
     * 秘钥文件的位置+名字
     */
    @Value("${encrypt.location}")
    private String location;

    /**
     * 秘钥文件的访问密码
     */
    @Value("${encrypt.secret}")
    private String secret;

    /**
     * 秘钥的别名
     */
    @Value("${encrypt.alias}")
    private String alias;

    /**
     * 秘钥的访问密码
     */
    @Value("${encrypt.password}")
    private String password;

    /**
     * 加载私钥到容器
     * @return
     */
    @Bean
    public RSAPrivateKey guiguPrivateKey(){
        //加载classpath下的秘钥文件
        ClassPathResource classPathResource = new ClassPathResource(location);
        //秘钥的工厂对象,加载秘钥文件,并且通过密码打开文件
        KeyStoreKeyFactory keyStoreKeyFactory =
                new KeyStoreKeyFactory(classPathResource, secret.toCharArray());
        //获取钥匙,通过别名+秘钥的访问密码获取
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias, password.toCharArray());
        //获取私钥,注入容器
        return (RSAPrivateKey)keyPair.getPrivate();
    }
}
